package com.ncmem.up6.store.obs;

import com.ncmem.up6.model.FileInf;
import com.obs.services.ObsClient;
import com.obs.services.model.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ObsTool {
    public ObsTool() {
    }

    public static ObsClient client(){
        ObsConfig cfg = new ObsConfig();
        ObsClient obsClient = new ObsClient(cfg.ak,cfg.sk,cfg.endpoint);
        return obsClient;
    }

    /**
     * API：
     * 	https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/API/API_PutObject.html
     * @param key 文件名称,QQ.exe
     * @param data
     */
    public static String putObject(String key,byte[] data) {

        ObsConfig cfg = new ObsConfig();
        ObsClient client = ObsTool.client();
        client.putObject(cfg.bucket,key,new ByteArrayInputStream(data));
        return "";
    }

    /**
     * API：
     * 	https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/API/API_GetObject.html
     * @param key 以左斜杠开始的资源路径。/guid/QQ.exe径
     * @param blockOffset
     * @param blockLen
     * @return
     */
    public static byte[] getObject(String key,long blockOffset,long blockLen) throws IOException {
        ObsConfig cfg = new ObsConfig();
        ObsClient client = new ObsClient(cfg.ak,cfg.sk,cfg.endpoint);
        //删除最前面的/
        if(key.startsWith("/")) key = key.substring(1);
        GetObjectRequest request = new GetObjectRequest(cfg.bucket, key);
        request.setRangeStart(blockOffset);
        request.setRangeEnd(blockOffset + blockLen-1);
        ObsObject obj = client.getObject(request);

        // 读取数据
        byte[] buf = new byte[1024];
        InputStream in = obj.getObjectContent();
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        for (int n = 0; n != -1&&blockLen>0; ) {
            n = in.read(buf, 0, buf.length);
            blockLen-=n;
            baos.write(buf,0,n);
        }

        in.close();
        return baos.toByteArray();
    }

    /**
     * API：
     * 	https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/API/API_CreateMultipartUpload.html
     * @param key guid/QQ.exe，
     * @return
     */
    public static String CreateMultipartUpload(String key) {
        ObsConfig cfg = new ObsConfig();
        ObsClient obsClient = new ObsClient(cfg.ak,cfg.sk,cfg.endpoint);

        InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(cfg.bucket, key);
        ObjectMetadata metadata = new ObjectMetadata();
        //metadata.addUserMetadata("property", "property-value");
        metadata.setContentType("application/octet-stream; charset=utf-8");
        request.setMetadata(metadata);
        InitiateMultipartUploadResult result = obsClient.initiateMultipartUpload(request);

        String uploadId = result.getUploadId();
        return uploadId;
    }

    /**
     * API:
     * 	https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/API/API_UploadPart.html
     * @param key /guid/QQ.exe
     * @param file 基于1
     * @param data
     */
    public static String UploadPart(String key,FileInf file,byte[] data) {
        ObsConfig cfg = new ObsConfig();

        // 创建ObsClient实例
        UploadPartRequest request = new UploadPartRequest(cfg.bucket, key);
        request.setUploadId(file.object_id);
        request.setPartNumber(file.blockIndex);
        request.setPartSize((long)data.length);
        request.setOffset(file.blockOffset);
        ByteArrayInputStream bin = new ByteArrayInputStream(data);
        request.setInput(bin);

        ObsClient client = new ObsClient(cfg.ak,cfg.sk,cfg.endpoint);
        UploadPartResult result = client.uploadPart(request);
        return result.getEtag();
    }

    /**
     * 参数：pathSvr,minio_id(UploadId)
     * API:
     * 	https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/API/API_CompleteMultipartUpload.html
     * POST /Key+?uploadId=UploadId HTTP/1.1
     Host: Bucket.s3.amazonaws.com
     <?xml version="1.0" encoding="UTF-8"?>
     <CompleteMultipartUpload xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
     <Part>
     <ChecksumCRC32>string</ChecksumCRC32>
     <ChecksumCRC32C>string</ChecksumCRC32C>
     <ChecksumSHA1>string</ChecksumSHA1>
     <ChecksumSHA256>string</ChecksumSHA256>
     <ETag>string</ETag>
     <PartNumber>integer</PartNumber>
     </Part>
     ...
     </CompleteMultipartUpload>

     * @param file
     */
    public static boolean CompleteMultipartUpload(FileInf file)
    {
        ObsConfig cfg = new ObsConfig();

        List<PartEtag> etags =file.etagsObs();
        CompleteMultipartUploadRequest request = new CompleteMultipartUploadRequest(cfg.bucket, file.ObsKey(), file.object_id, etags);

        System.setProperty("javax.xml.parsers.DocumentBuilderFactory","com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");

        ObsClient client = ObsTool.client();
        CompleteMultipartUploadResult res = client.completeMultipartUpload(request);
        System.out.println(res.getStatusCode());
        return res.getStatusCode() == 200;
    }
}
